package qr.game;

import qr.game.fragments.LeaderboardFragment;
import qr.game.fragments.LocationsFragment;
import qr.game.fragments.MapFragment;
import qr.game.rest.RestClient;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.Toast;

public class GameActivity extends FragmentActivity {

    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
       
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        Tab tab = actionBar.newTab()
                .setText("Locations")
                .setTabListener(new TabListener<LocationsFragment>(
                        this, "location", LocationsFragment.class));
        actionBar.addTab(tab);

        tab = actionBar.newTab()
                .setText("Map")
                .setTabListener(new TabListener<MapFragment>(
                        this, "map", MapFragment.class));
            actionBar.addTab(tab);
        
        tab = actionBar.newTab()
            .setText("Leaderboard")
            .setTabListener(new TabListener<LeaderboardFragment>(
                    this, "leaderboard", LeaderboardFragment.class));
        actionBar.addTab(tab);
        
       
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_settings:
        	SharedPreferences p = getSharedPreferences("qrcode", MODE_MULTI_PROCESS);
        	Editor e = p.edit();
        	e.remove("username");
        	e.commit();
        	finish();
        	Intent myIntent = new Intent(getBaseContext(), LoginActivity.class);
            startActivityForResult(myIntent, 0);
            return true;
        }
        return false;
    }


    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
                getActionBar().getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        MenuItem checkin = menu.findItem(R.id.menu_checkin);
        checkin.setOnMenuItemClickListener( new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
				// 2. Chain together various setter methods to set the dialog characteristics
				builder.setMessage("For best performance hold camera parallel to QR code")
				       .setTitle("QR Game");
				// 3. Get the AlertDialog from create()
				builder.setNeutralButton("OK", new OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
				        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				        startActivityForResult(intent, 0);
					}
					

				});
				AlertDialog dialog = builder.create();
				return true;
			}
		});
        return true;
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String r = intent.getStringExtra("SCAN_RESULT");
				String username = getSharedPreferences("qrcode", MODE_MULTI_PROCESS).getString("username", "");
                boolean ok = RestClient.getRestClient().enterLocation(username,r);
                String display;
                if( ok ){
                	display = "Successfully found location.";
					Intent next = new Intent( this, LocationViewActivity.class );
					next.putExtra("location", r );
					startActivity(next);
                }else{
                	display = "Unknown location.";
                }
                Toast.makeText(getApplication(), display, Toast.LENGTH_LONG).show();
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }

    
    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
        private android.app.Fragment mFragment;
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;

        /** Constructor used each time a new tab is created.
          * @param activity  The host Activity, used to instantiate the fragment
          * @param tag  The identifier tag for the fragment
          * @param clz  The fragment's Class, used to instantiate the fragment
          */
        public TabListener(Activity activity, String tag, Class<T> clz) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
        }

        /* The following are each of the ActionBar.TabListener callbacks */

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // Check if the fragment is already initialized
        	if(tab.getText().equals("Map")){
        		Toast.makeText(mActivity, "Coming soon!", Toast.LENGTH_LONG).show();
        		return;
        	}
            if (mFragment == null) {
                // If not, instantiate and add it to the activity
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                // If it exists, simply attach it in order to show it
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Usually do nothing.
        }
    }
    
}
